#include "glminimal.h"

#pragma comment( lib, "glew32.lib" )
////#pragma comment( lib, "glew32s.lib" )
//#pragma comment( lib, "glfw.lib" )
//#pragma comment( lib, "opengl32.lib" ) // not needed?

//#pragma comment( lib, "glu32.lib" )
//#pragma comment( lib, "user32.lib" )

//#define GLEW_STATIC

#include <GL\glew.h> // Glew before GLFW! ifndef magik
#include <GL\glfw.h>

#include <iostream>



void GLMinimal::reshape( int w, int h )
{
	this->resX = w;
	this->resY = h;
	glViewport( 0, 0, (GLsizei)w, (GLsizei)h );

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glFrustum(-1.f,1.f,-1.f,1.f,0.01f, 1000.f);
	glMatrixMode(GL_MODELVIEW);
}


GLMinimal::GLMinimal(int width, int height, std::string title)
{
	time = 0.0;
	dt = 0.0;
	oldtime = 0.0;

	resX = width;
	resY = height;
	this->title = title;
	init();
}

GLMinimal::~GLMinimal()
{
#ifdef _DEBUG
	std::cout << "dtor" << std::endl;
#endif
	glfwTerminate();
}

void GLMinimal::init()
{
	bool isInit = glfwInit();

	if( !isInit || !glfwOpenWindow( resX,resY, 0,0,0,0,0,0, GLFW_WINDOW ) ) // wid,hei,rbits,gbits,bbits,depthbits,colorbits
	{
    fprintf(stderr, "glminimal: glfw initialization error. Could be a bad window mode.\n");
		glfwTerminate();
		exit(0);
		return;
	}
	glfwSetWindowTitle( title.c_str() );
	//glfwSetWindowSizeCallback( &GLMinimal::reshape );
	glfwEnable( GLFW_STICKY_KEYS );
	glfwSwapInterval( 0 ); // num of retraces to wait before swapBuffers. 0 is vsync off.
	glfwSetTime( 0.0 );

	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		/* Problem: glewInit failed, something is seriously wrong. */
		fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
		exit(0);
	}
	fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));

	if(GLEW_VERSION_3_1)
	{
		std::cout << "Hardware supports OpenGL 3.1" << std::endl;
	}
	else
	{
		std::cout << "Fail: Hardware doesn't support OpenGL 3.1" << std::endl;
	}
}

void GLMinimal::update()
{
	/* Timing */
	time = glfwGetTime();
	dt = time - oldtime;
	oldtime = time;


	/* Swap buffers */
	glfwSwapBuffers();

	/* See if window resized. Could use callback instead... */
	int newX, newY;
	glfwGetWindowSize(&newX,&newY);
	if(resX != newX || newY != newY)
	{
		reshape(newX,newY);
	}
}

bool GLMinimal::isWindowOpen()
{
	return glfwGetWindowParam(GLFW_OPENED);
}
